from st77352 import TFT
from machine import SPI,Pin
import time
#hardware SPI, HSPI
spi=SPI(1,baudrate=40000000, polarity=0, phase=0, sck=Pin(2), mosi=Pin(3))
tft=TFT(spi,6,10,7)# dc, rst, cs   #6,10,7 aDC, aReset, aCS
tft.rgb(False)
tft.init_7735(tft.REDTAB80x160)
tft.rotation(0)

# 用于存储BMP图片的缓冲区
BMPBuffer = bytearray(160 * 80*2)  # 一个缓冲区，用于存储RGB565数据

def show_pic(file='t2.bmp'):
    with open(file, "rb") as f:
        f.seek(18)  # 水平分辨率
        buff = f.read(4)
        HResolution = buff[3] * 1024 + buff[2] * 512 + buff[1] * 256 + buff[0]
        print("图片水平分辨率：", HResolution, "像素")

        f.seek(22)  # 垂直分辨率
        buff = f.read(4)
        VResolution = buff[3] * 1024 + buff[2] * 512 + buff[1] * 256 + buff[0]

        print("图片垂直分辨率：", VResolution, "像素")

        # 计算图片每行占用的字节数（向上往4的整数倍靠）
        if HResolution * 3 % 4 == 0:
            bytesPerRow = (HResolution * 3 // 4) * 4
        else:
            bytesPerRow = (HResolution * 3 // 4 + 1) * 4

        cnt = 0
        for rowCnt in range(VResolution - 1, -1, -1):  # 行号要倒着来
            f.seek(bytesPerRow * rowCnt + 54)  # 偏移量54，因为图像数据是从54字节开始的
            for cntInARow in range(int(bytesPerRow / 3)):  # 读取行中的有效数据
                buff = f.read(3)  # RGB888格式，一次读取3字节
                blue = buff[0] & 0xf8
                green = buff[1] & 0xfc
                red = buff[2] & 0xf8
                BMPBuffer[0 + cnt * 2] = red | (green & 0xe0) >> 5
                BMPBuffer[1 + cnt * 2] = (blue >> 3) | ((green & 0x1b) << 3)
                cnt += 1

        tft.image(data=BMPBuffer,x0=0, y0=0, x1=79, y1=159)

        # 清理不再需要的变量
        del buff
#         gc.collect()  # 强制进行垃圾回收

def main():
    while True:
        show_pic("t1.bmp")
        time.sleep(1)
        show_pic("t2.bmp")
        time.sleep(1)
        

if __name__ == "__main__":
    main()